<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票财务分析数据统计</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    
    <style>
        .stat-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .stat-value {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .stat-label {
            font-size: 16px;
            opacity: 0.9;
        }
        .chart-container {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 30px;
            background-color: #f9f9f9;
        }
        .chart-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: center;
            color: #333;
        }
        .chart {
            width: 100%;
            height: 400px;
        }
        .back-link {
            margin-bottom: 20px;
        }
        .recommendation-section {
            background-color: #e7f3ff;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 30px;
            border-left: 4px solid #007bff;
        }
        .recommendation-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #007bff;
        }
        .recommendation-list {
            list-style-type: none;
            padding-left: 20px;
        }
        .recommendation-list li {
            position: relative;
            padding-left: 20px;
            margin-bottom: 10px;
        }
        .recommendation-list li:before {
            content: "▶";
            position: absolute;
            left: 0;
            color: #007bff;
        }
        .data-table {
            margin-top: 20px;
        }
        .table th, .table td {
            text-align: center;
            vertical-align: middle;
        }
        .loading {
            text-align: center;
            padding: 100px;
            font-size: 20px;
            color: #666;
        }
    </style>
</head>
<body>
<div class="container">
    <a href="/stockpe/list" class="back-link btn btn-secondary">
        <i class="fas fa-arrow-left"></i> 返回列表
    </a>
    
    <h1 class="mt-5 mb-4">股票财务分析数据统计</h1>
    
    <div class="loading" id="loading">
        <i class="fas fa-spinner fa-spin"></i> 加载统计数据中...
    </div>
    
    <div id="statisticsContent" style="display: none;">
        <!-- 核心指标统计卡片 -->
        <div class="row mb-5">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-value" id="totalCount">0</div>
                    <div class="stat-label">股票总数</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <div class="stat-value" id="averagePE">0.00</div>
                    <div class="stat-label">平均市盈率(TTM)</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                    <div class="stat-value" id="averageROE">0.00%</div>
                    <div class="stat-label">平均ROE(TTM)</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                    <div class="stat-value" id="lowPERatioCount">0</div>
                    <div class="stat-label">低估值股票数(PE<10)</div>
                </div>
            </div>
        </div>
        
        <!-- 投资建议 -->
        <div class="recommendation-section">
            <h3 class="recommendation-title">投资建议</h3>
            <ul class="recommendation-list" id="recommendations">
                <li>加载中...</li>
            </ul>
        </div>
        
        <!-- 市盈率分布图 -->
        <div class="chart-container">
            <div class="chart-title">市盈率(TTM)分布情况</div>
            <div id="peChart" class="chart"></div>
        </div>
        
        <!-- ROE分布图 -->
        <div class="chart-container">
            <div class="chart-title">ROE(TTM)分布情况</div>
            <div id="roeChart" class="chart"></div>
        </div>
        
        <!-- PE-ROE散点图 -->
        <div class="chart-container">
            <div class="chart-title">PE-ROE分布散点图</div>
            <div id="peRoeScatterChart" class="chart"></div>
        </div>
        
        <!-- 行业分布 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">行业分布饼图</div>
                    <div id="industryChart" class="chart"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <div class="chart-title">估值等级分布</div>
                    <div id="valuationChart" class="chart"></div>
                </div>
            </div>
        </div>
        
        <!-- 优质股票列表 -->
        <div class="mt-5">
            <h3 class="mb-3">优质股票推荐（低PE高ROE）</h3>
            <div class="table-responsive">
                <table class="table table-striped table-bordered data-table">
                    <thead>
                        <tr>
                            <th>股票代码</th>
                            <th>股票名称</th>
                            <th>市盈率(TTM)</th>
                            <th>ROE(TTM)</th>
                            <th>PE/ROE比率</th>
                            <th>估值评级</th>
                        </tr>
                    </thead>
                    <tbody id="qualityStockTable">
                        <tr>
                            <td colspan="6" class="text-center">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        loadStatisticsData();
    });
    
    // 加载统计数据
    function loadStatisticsData() {
        $.ajax({
            url: '/stockpe/statisticsData',
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    // 显示统计内容
                    $('#loading').hide();
                    $('#statisticsContent').show();
                    
                    // 更新核心指标
                    $('#totalCount').text(response.totalCount);
                    $('#averagePE').text(response.averagePE);
                    $('#averageROE').text(response.averageROE + '%');
                    
                    // 计算低估值股票数
                    let lowPERatioCount = 0;
                    if (response.peDistribution && response.peDistribution['< 10']) {
                        lowPERatioCount = response.peDistribution['< 10'];
                    }
                    $('#lowPERatioCount').text(lowPERatioCount);
                    
                    // 生成投资建议
                    generateRecommendations(response);
                    
                    // 绘制图表
                    drawPEChart(response.peDistribution);
                    drawROEChart(response.roeDistribution);
                    drawPERoeScatterChart();
                    drawIndustryChart();
                    drawValuationChart(response.peDistribution, response.roeDistribution);
                    
                    // 生成优质股票列表
                    generateQualityStockList(response);
                } else {
                    $('#loading').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#loading').html('<div class="alert alert-danger">数据加载失败，请稍后重试</div>');
            }
        });
    }
    
    // 生成投资建议
    function generateRecommendations(data) {
        let recommendations = [];
        const avgPE = parseFloat(data.averagePE);
        const avgROE = parseFloat(data.averageROE);
        
        // 根据平均PE和ROE生成建议
        if (avgPE < 15) {
            recommendations.push('当前市场整体估值较低，具备较好的投资价值');
        } else if (avgPE > 30) {
            recommendations.push('当前市场整体估值较高，投资需谨慎，建议关注业绩稳定增长的低估值个股');
        } else {
            recommendations.push('当前市场估值处于合理区间，建议均衡配置');
        }
        
        if (avgROE > 15) {
            recommendations.push('市场整体盈利能力较强，可适当提高权益资产配置比例');
        } else if (avgROE < 10) {
            recommendations.push('市场整体盈利能力偏弱，建议关注高ROE板块和个股');
        }
        
        // 添加低估值建议
        if (data.peDistribution && data.peDistribution['< 10'] > 0) {
            recommendations.push(`有${data.peDistribution['< 10']}只股票市盈率低于10，可重点关注这些低估值机会`);
        }
        
        // 添加高ROE建议
        if (data.roeDistribution) {
            let highROECount = 0;
            if (data.roeDistribution['15-20%']) highROECount += data.roeDistribution['15-20%'];
            if (data.roeDistribution['20-30%']) highROECount += data.roeDistribution['20-30%'];
            if (data.roeDistribution['> 30%']) highROECount += data.roeDistribution['> 30%'];
            
            if (highROECount > 0) {
                recommendations.push(`有${highROECount}只股票ROE高于15%，这些股票盈利能力较强`);
            }
        }
        
        // 渲染建议列表
        let html = '';
        recommendations.forEach(item => {
            html += `<li>${item}</li>`;
        });
        $('#recommendations').html(html);
    }
    
    // 绘制PE分布图
    function drawPEChart(peDistribution) {
        const chart = echarts.init(document.getElementById('peChart'));
        
        const data = [];
        const categories = ['负值', '< 10', '10-20', '20-30', '30-50', '50-100', '> 100'];
        
        categories.forEach(cat => {
            if (peDistribution && peDistribution[cat]) {
                data.push(peDistribution[cat]);
            } else {
                data.push(0);
            }
        });
        
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    return params[0].name + ': ' + params[0].value + '只';
                }
            },
            xAxis: {
                type: 'category',
                data: categories,
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '股票数量'
            },
            series: [{
                data: data,
                type: 'bar',
                itemStyle: {
                    color: function(params) {
                        const colors = ['#ff4d4f', '#52c41a', '#faad14', '#fa8c16', '#1890ff', '#722ed1', '#eb2f96'];
                        return colors[params.dataIndex];
                    }
                },
                label: {
                    show: true,
                    position: 'top'
                }
            }]
        };
        
        chart.setOption(option);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 绘制ROE分布图
    function drawROEChart(roeDistribution) {
        const chart = echarts.init(document.getElementById('roeChart'));
        
        const data = [];
        const categories = ['负值', '< 5%', '5-10%', '10-15%', '15-20%', '20-30%', '> 30%'];
        
        categories.forEach(cat => {
            if (roeDistribution && roeDistribution[cat]) {
                data.push(roeDistribution[cat]);
            } else {
                data.push(0);
            }
        });
        
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    return params[0].name + ': ' + params[0].value + '只';
                }
            },
            xAxis: {
                type: 'category',
                data: categories,
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '股票数量'
            },
            series: [{
                data: data,
                type: 'bar',
                itemStyle: {
                    color: function(params) {
                        const colors = ['#ff4d4f', '#ff7a45', '#faad14', '#fa8c16', '#13c2c2', '#52c41a', '#1890ff'];
                        return colors[params.dataIndex];
                    }
                },
                label: {
                    show: true,
                    position: 'top'
                }
            }]
        };
        
        chart.setOption(option);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 绘制PE-ROE散点图
    function drawPERoeScatterChart() {
        const chart = echarts.init(document.getElementById('peRoeScatterChart'));
        
        // 模拟数据，实际项目中应该从后端获取
        const mockData = [
            [25.5, 12.3, '000063', '中兴通讯'],
            [18.2, 15.6, '003009', '中天火箭'],
            [12.8, 8.5, '000002', '万科A'],
            [35.2, 22.8, '000858', '五粮液'],
            [6.5, 10.2, '000001', '平安银行'],
            [22.3, 18.5, '000895', '双汇发展'],
            [15.7, 14.2, '002415', '海康威视'],
            [42.8, 25.6, '300750', '宁德时代'],
            [9.2, 7.8, '601318', '中国平安'],
            [28.6, 16.3, '600519', '贵州茅台']
        ];
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    return `${params.value[3]}(${params.value[2]})<br/>` +
                           `市盈率: ${params.value[0]}<br/>` +
                           `ROE: ${params.value[1]}%`;
                }
            },
            xAxis: {
                type: 'value',
                name: '市盈率(TTM)',
                min: 0,
                max: 50
            },
            yAxis: {
                type: 'value',
                name: 'ROE(TTM)(%)',
                min: 0,
                max: 30
            },
            series: [{
                symbolSize: 8,
                data: mockData,
                type: 'scatter',
                itemStyle: {
                    color: function(params) {
                        // PE越低，ROE越高，颜色越绿
                        const pe = params.value[0];
                        const roe = params.value[1];
                        const score = roe / pe; // 投资价值评分
                        
                        if (score > 0.8) return '#52c41a';
                        if (score > 0.5) return '#1890ff';
                        if (score > 0.3) return '#faad14';
                        return '#ff7a45';
                    }
                }
            }]
        };
        
        chart.setOption(option);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 绘制行业分布饼图
    function drawIndustryChart() {
        const chart = echarts.init(document.getElementById('industryChart'));
        
        // 模拟行业分布数据
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                name: '行业分布',
                type: 'pie',
                radius: '50%',
                data: [
                    {value: 3, name: '科技'}, 
                    {value: 2, name: '金融'},
                    {value: 2, name: '消费'},
                    {value: 1, name: '房地产'},
                    {value: 1, name: '医药'},
                    {value: 1, name: '新能源'}
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        
        chart.setOption(option);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 绘制估值等级分布
    function drawValuationChart(peDistribution, roeDistribution) {
        const chart = echarts.init(document.getElementById('valuationChart'));
        
        // 计算估值等级分布
        let undervalued = 0;  // PE<10 且 ROE>15%
        let reasonable = 0;   // PE10-30 且 ROE10-20%
        let overvalued = 0;   // PE>30 或 ROE<5%
        
        // 模拟计算，实际项目中应该从数据中统计
        undervalued = 2;
        reasonable = 5;
        overvalued = 3;
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                name: '估值等级',
                type: 'pie',
                radius: '50%',
                data: [
                    {value: undervalued, name: '低估值', itemStyle: {color: '#52c41a'}},
                    {value: reasonable, name: '合理估值', itemStyle: {color: '#1890ff'}},
                    {value: overvalued, name: '高估值', itemStyle: {color: '#ff4d4f'}}
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        
        chart.setOption(option);
        
        // 响应式处理
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 生成优质股票列表
    function generateQualityStockList(data) {
        // 模拟优质股票数据
        const qualityStocks = [
            {code: '000001', name: '平安银行', pe: 6.5, roe: 10.2, ratio: 0.637},
            {code: '000002', name: '万科A', pe: 12.8, roe: 8.5, ratio: 1.506},
            {code: '000063', name: '中兴通讯', pe: 25.5, roe: 12.3, ratio: 2.073},
            {code: '000895', name: '双汇发展', pe: 22.3, roe: 18.5, ratio: 1.205},
            {code: '002415', name: '海康威视', pe: 15.7, roe: 14.2, ratio: 1.106}
        ];
        
        // 按PE/ROE比率排序（值越小越优质）
        qualityStocks.sort((a, b) => a.ratio - b.ratio);
        
        let html = '';
        qualityStocks.forEach(stock => {
            let rating = '低估值';
            let ratingClass = 'text-success';
            
            if (stock.ratio > 2) {
                rating = '高估值';
                ratingClass = 'text-danger';
            } else if (stock.ratio > 1) {
                rating = '合理估值';
                ratingClass = 'text-warning';
            }
            
            html += `
            <tr>
                <td>${stock.code}</td>
                <td>${stock.name}</td>
                <td class="${stock.pe < 10 ? 'text-success' : 'text-danger'}">${stock.pe}</td>
                <td class="${stock.roe > 15 ? 'text-success' : stock.roe > 10 ? 'text-warning' : 'text-danger'}">${stock.roe}%</td>
                <td>${stock.ratio.toFixed(3)}</td>
                <td class="${ratingClass}">${rating}</td>
            </tr>
            `;
        });
        
        $('#qualityStockTable').html(html);
    }
</script>
</body>
</html>